package com.miao.hong.fang.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ContextLoaderListener implements ServletContextListener{

	private DefaultListableBeanFactory factory;
	
	public void contextDestroyed(ServletContextEvent arg0) {
		
	}

	public void contextInitialized(ServletContextEvent event) {
		final DefaultListableBeanFactory factory = getConfigurableBeanFactory(event.getServletContext());
		SpringBeansHolder holder = new SpringBeansHolder();
		holder.injectBeans(factory);
		
	}
	
    public DefaultListableBeanFactory getConfigurableBeanFactory(ServletContext servletContext) {
        if (factory == null) {

            ConfigurableWebApplicationContext context = (ConfigurableWebApplicationContext) WebApplicationContextUtils
                    .getRequiredWebApplicationContext(servletContext);

            if (context == null) {
                throw new IllegalStateException("This listener requires Spring's context to be initialized first. "
                        + "Make sure you have defined Spring's context loader listener "
                        + "(org.springframework.web.context.ContextLoaderListener) correctly in your web.xml. "
                        + "If it's already defined, make sure that this listener is "
                        + "defined AFTER spring's context loader listener.");
            }

            factory = (DefaultListableBeanFactory) context.getBeanFactory();
        }
        return factory;
    }


}
